import React, { useEffect, useState, useRef } from 'react';
import { connect } from 'umi';
import useResizeObserver from '@react-hook/resize-observer';
import { useThemeChange } from '@/hooks';
import { getCssVariableValue } from '@/utils/utils';
import styles from './index.less';

export const CentralizedEcharts = (props) => {
  const target = useRef(null);
  const [chartIns, setChartIns] = useState();
  const [size, setSize] = useState({});
  const { theme } = useThemeChange();

  // 监听容器尺寸变化
  useResizeObserver(target, (entry) => setSize(entry.contentRect));

  // 当容器尺寸发生改变时，重新渲染echarts图
  useEffect(() => {
    if (chartIns && size.width) {
      chartIns.resize();
    }
  }, [size.width]);

  // 当echart图数据发生变化时，重新初始化echarts图
  useEffect(() => {
    if (!props.sequenceProportionChartDate) return;
    initEcharts();
  }, [props.sequenceProportionChartDate, theme]);

  const initEcharts = () => {
    const xData = [
      '0100',
      '0200',
      '0300',
      '0400',
      '0500',
      '0600',
      '0700',
      '0800',
      '0900',
      '1000',
      '1100',
      '1200',
      '1300',
      '1400',
      '1500',
      '1600',
      '1700',
      '1800',
      '1900',
      '2000',
      '2100',
      '2200',
      '2300',
      '2400',
    ];
    const {
      monthQuantity,
      periodQuantity,
      dayQuantity,
      sumAvgPrice,
      monthAvgPrice,
      periodAvgPrice,
      dayAvgPrice,
    } = props.sequenceProportionChartDate;

    var chartDom = document.getElementById('sequenceEcharts');
    var myChart = echarts.init(chartDom);
    setChartIns(myChart);

    let colorList = ['#527CCD', '#65B1CF', '#CBA019', '#67DCAB', '#5E92F6', '#76D4F9', '#F5BE15'];

    myChart.setOption(
      {
        animation: false,
        color: colorList,
        legend: {
          bottom: 0,
          textStyle: {
            color: getCssVariableValue('--chart-legend-color'),
          },
          left: 'center',
          itemGap: 13,
          itemWidth: 16,
          itemHeight: 8,
          data: [
            '月中长期成交电量',
            '旬中长期成交电量',
            '日中长期成交电量',
            {
              name: '汇总加权均价',
              // itemStyle: {
              //   color: '#222629',
              //   borderWidth: 1,
              //   borderColor: colorList[3],
              // },
            },
            {
              name: '月中长期加权均价',
              // itemStyle: {
              //   color: '#222629',
              //   borderWidth: 1,
              //   borderColor: colorList[4],
              // },
            },
            {
              name: '旬中长期加权均价',
              // itemStyle: {
              //   color: '#222629',
              //   borderWidth: 1,
              //   borderColor: colorList[5],
              // },
            },
            {
              name: '日中长期加权均价',
              // itemStyle: {
              //   color: '#222629',
              //   borderWidth: 1,
              //   borderColor: colorList[6],
              // },
            },
          ],
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: '#161A1D',
          borderColor: 'transparent',
          textStyle: {
            color: '#d3d4d4',
          },
          formatter: (params) => {
            let upPart = ['月中长期成交电量', '旬中长期成交电量', '日中长期成交电量'];
            let upPartString = [];
            let downPart = [
              '汇总加权均价',
              '月中长期加权均价',
              '旬中长期加权均价',
              '日中长期加权均价',
            ];
            let downPartString = [];
            upPart.forEach((upItem) => {
              params.forEach((paramsItem) => {
                if (upItem === paramsItem.seriesName) {
                  upPartString.push(`
                    <div style="width: 230px; height:24px; line-height: 24px; display:flex; justify-content:space-between;">
                      <span>${paramsItem.marker} ${paramsItem.seriesName}</span>
                      <span>${paramsItem.data.toFixed(3)}</span>
                    </div>
                  `);
                }
              });
            });
            downPart.forEach((downItem) => {
              params.forEach((paramsItem) => {
                if (downItem === paramsItem.seriesName) {
                  downPartString.push(`
                    <div style="width: 230px; height:24px; line-height: 24px; display:flex; justify-content:space-between;">
                      <span>${paramsItem.marker} ${paramsItem.seriesName}</span>
                      <span>${paramsItem.data.toFixed(2)}</span>
                    </div>
                  `);
                }
              });
            });
            let str = `
              <div style="color: #7A7D7F;">${params[0].name}</div>
                <div style="color: #A7A8A9;">
            `;
            str += upPartString.join('');
            if (upPartString.length && downPartString.length) {
              str += `
                <div style="width: 230px; height:0; border-top:1px solid #4E5154; margin: 6px 0;"></div>
              `;
            }
            str += downPartString.join('');
            str += `</div>`;
            return str;
          },
        },
        axisPointer: {
          link: [
            {
              xAxisIndex: 'all',
            },
          ],
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
            type: 'solid',
          },
        },
        toolbox: {
          show: false,
        },
        grid: [
          {
            top: '40',
            left: '52',
            right: '0',
            height: '353',
          },
          {
            left: '52',
            right: '0',
            top: '452',
            height: '140',
          },
        ],
        xAxis: [
          {
            type: 'category',
            data: xData,
            axisLine: {
              lineStyle: {
                color: getCssVariableValue('--chart-x-line'),
              },
            },
            axisLabel: {
              color: getCssVariableValue('--chart-font-color'),
            },
            axisTick: {
              alignWithLabel: true,
            },
          },
          {
            type: 'category',
            gridIndex: 1,
            data: xData,
            axisLine: {
              lineStyle: {
                color: getCssVariableValue('--chart-x-line'),
              },
            },
            axisLabel: {
              show: false,
            },
            axisTick: {
              show: false,
            },
          },
        ],
        yAxis: [
          {
            type: 'value',
            name: 'MWh',
            nameTextStyle: {
              color: getCssVariableValue('--chart-font-color'),
            },
            // scale: true,
            axisLine: {
              show: false,
            },
            splitLine: {
              lineStyle: {
                color: getCssVariableValue('--chart-y-line'),
              },
            },
            axisLabel: {
              color: getCssVariableValue('--chart-font-color'),
            },
          },
          {
            gridIndex: 1,
            type: 'value',
            name: '元/MWh',
            nameTextStyle: {
              color: getCssVariableValue('--chart-font-color'),
            },
            // scale: true,
            axisLine: {
              show: false,
            },
            splitLine: {
              lineStyle: {
                color: getCssVariableValue('--chart-y-line'),
              },
            },
            axisLabel: {
              color: getCssVariableValue('--chart-font-color'),
            },
          },
        ],
        series: [
          {
            name: '月中长期成交电量',
            type: 'bar',
            stack: 'quantity',
            barWidth: 16,
            data: monthQuantity,
          },
          {
            name: '旬中长期成交电量',
            type: 'bar',
            stack: 'quantity',
            barWidth: 16,
            data: periodQuantity,
          },
          {
            name: '日中长期成交电量',
            type: 'bar',
            stack: 'quantity',
            barWidth: 16,
            data: dayQuantity,
          },
          {
            name: '汇总加权均价',
            type: 'line',
            xAxisIndex: 1,
            yAxisIndex: 1,
            data: sumAvgPrice,
            smooth: true,
            symbol: 'none',
            lineStyle: {
              width: 1,
            },
          },
          {
            name: '月中长期加权均价',
            type: 'line',
            xAxisIndex: 1,
            yAxisIndex: 1,
            data: monthAvgPrice,
            smooth: true,
            symbol: 'none',
            lineStyle: {
              width: 1,
            },
          },
          {
            name: '旬中长期加权均价',
            type: 'line',
            xAxisIndex: 1,
            yAxisIndex: 1,
            data: periodAvgPrice,
            smooth: true,
            symbol: 'none',
            lineStyle: {
              width: 1,
            },
          },
          {
            name: '日中长期加权均价',
            type: 'line',
            xAxisIndex: 1,
            yAxisIndex: 1,
            data: dayAvgPrice,
            smooth: true,
            symbol: 'none',
            lineStyle: {
              width: 1,
            },
          },
        ],
      },
      true,
    );
  };

  return (
    <div ref={target} id="sequenceEcharts" className={styles.CentralizedEcharts}>
      {''}
    </div>
  );
};

const mapStateToProps = ({ mediumAndLongTermMarket }) => ({
  sequenceProportionChartDate: mediumAndLongTermMarket.sequenceProportionChartDate,
});

const mapDispatchToProps = {};

export default connect(mapStateToProps, mapDispatchToProps)(CentralizedEcharts);
